package com.irdstudio.efp.nls.service.impl.psd.apply;

import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.EsbRetCodeStandard;
import com.irdstudio.basic.framework.core.constant.TimeType;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.basic.framework.core.exception.OcmSystemException;
import com.irdstudio.basic.framework.core.util.MessageRuleCheckUtil;
import com.irdstudio.basic.framework.core.util.StringUtil;
import com.irdstudio.basic.framework.core.util.UUIDUtil;
import com.irdstudio.efp.console.common.ConsoleConstant;
import com.irdstudio.efp.console.common.psd.PsdConstantSet;
import com.irdstudio.efp.console.service.facade.SOrgService;
import com.irdstudio.efp.console.service.vo.SOrgVO;
import com.irdstudio.efp.ctr.service.facade.CtrLoanContService;
import com.irdstudio.efp.ctr.service.vo.CtrLoanContVO;
import com.irdstudio.efp.cus.service.facade.CusIndivService;
import com.irdstudio.efp.cus.service.vo.CusIndivVO;
import com.irdstudio.efp.edoc.service.bo.CfcaSignInfoVO;
import com.irdstudio.efp.edoc.service.bo.ImageBizDetailVO;
import com.irdstudio.efp.edoc.service.facade.CfcaSignInfoService;
import com.irdstudio.efp.edoc.service.facade.ImageBizDetailService;
import com.irdstudio.efp.edoc.service.facade.signature.PsdCertUploadService;
import com.irdstudio.efp.edoc.service.facade.signature.PsdContResult;
import com.irdstudio.efp.edoc.service.facade.signature.PsdContService;
import com.irdstudio.efp.esb.common.constant.ElectronicSignatureEnums;
import com.irdstudio.efp.limit.service.facade.LmtPrdContService;
import com.irdstudio.efp.limit.service.vo.LmtPrdContVO;
import com.irdstudio.efp.nls.service.facade.psd.PsdSqsSignatureService;
import com.irdstudio.efp.nls.service.facade.sx.NlsCreditInfoService;
import com.irdstudio.efp.nls.service.impl.SoltServiceImpl;
import com.irdstudio.efp.nls.service.impl.ctrloancont.ctr.PsdApplyCtrLoanCtr;
import com.irdstudio.efp.nls.service.impl.psd.apply.bean.SignContractBean;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;
import com.irdstudio.efp.nls.service.vo.queue.NlsProcessBizVO;
import com.irdstudio.efp.nls.service.vo.signature.SignatureRecordVO;
import com.irdstudio.efp.nls.service.vo.sx.NlsCreditInfoVO;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

import static com.irdstudio.efp.esb.common.constant.ElectronicSignatureConstant.CONT_STATUS_200;
import static com.irdstudio.efp.nls.common.constant.psd.NlsApplyFlowStatus.FLOW_STATUS_4;

/**
 * 需求编号：普税贷需求编号<br/>
 * 问题编号：<br/>
 * 功能描述：普税贷合同签订插槽<br/>
 * 开发人员：周才顺<br/>
 * 创建时间：2019/8/30 16:27
 *
 * @Author zhoucs1
 * @Version 1.0
 * @Since 1.0
 */
@Service("psdSignContractService")
public class PsdSignContractServiceImpl extends SoltServiceImpl {
    // 日志
    private static final Logger logger = LoggerFactory.getLogger(PsdSignContractServiceImpl.class);

    private boolean Flag = false;

    @Override
    public void doExecute(NlsProcessBizVO nlsProcessBizVo, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {
        //查询该笔用信对应的授信信息
        String applySeq = nlsApplyInfoVO.getApplySeq();
        try {
            logger.info("======>普税贷合同签订服务开始,流水号" + applySeq + "<======");
            NlsCreditInfoVO nlsCreditInfoVO = new NlsCreditInfoVO();
            nlsCreditInfoVO.setLmtApplySeq(nlsApplyInfoVO.getLmtApplySeq());
            nlsCreditInfoVO = nlsCreditInfoService.queryByPk(nlsCreditInfoVO);
            Optional.ofNullable(nlsCreditInfoVO).orElseThrow(() -> new OcmSystemException(EsbRetCodeStandard.WFJKYWGZ.getValue(), "用信申请流水号为【" + nlsApplyInfoVO.getApplySeq() + "】不存在授信"));


            JSONObject signContractJson = (JSONObject) nlsApplyInfoVO.getSignContractBean();
            SignContractBean signContractBean = new SignContractBean();

            CusIndivVO cusIndivVO = null;
            CfcaSignInfoVO cfcaSignInfoVO = null;
            if (Objects.isNull(signContractJson)) {
                //获取客户信息
                cusIndivVO = new CusIndivVO();
                cusIndivVO.setCusId(nlsCreditInfoVO.getCusId());
                cusIndivVO = signContractBean.getCusIndivVO(cusIndivService, cusIndivVO);
                // 获取合同签订信息
                cfcaSignInfoVO = new CfcaSignInfoVO();
                cfcaSignInfoVO.setApplySeq(applySeq);
                cfcaSignInfoVO = signContractBean.getCfcaSignInfoVO(cfcaSignInfoService, cfcaSignInfoVO);
            } else {
                cusIndivVO = signContractJson.getObject("cusIndivVO", CusIndivVO.class);
                cfcaSignInfoVO = signContractJson.getObject("cfcaSignInfoVO", CfcaSignInfoVO.class);
                signContractBean.setCusIndivVO(cusIndivVO);
                signContractBean.setCfcaSignInfoVO(cfcaSignInfoVO);
                nlsApplyInfoVO.setSignContractBean(signContractBean);
            }

            if (cusIndivVO == null || StringUtils.isEmpty(cusIndivVO.getAxqUsrId())) {
                if (logger.isErrorEnabled()) {
                    logger.error("普税贷合同签订服务 用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】通过【" + nlsApplyInfoVO.getCusId() + "】查询客户信息为空 或 安心签用户号为空 请核查!!!");
                    throw new OcmSystemException("普税贷合同签订服务 用信申请流水号【" + nlsApplyInfoVO.getApplySeq() + "】通过【" + nlsApplyInfoVO.getCusId() + "】查询客户信息为空 或 安心签用户号为空  请核查!!!");
                }
            }
            // 安心签开户号
            //if (StringUtils.isEmpty(cusIndivVO.getAxqUsrId())) {
            //    //  1.调用cfca签章开户
            //    PsdContResult psdContResult = psdContService.openAccount(cusIndivVO.getCusName(), cusIndivVO.getCertType(), cusIndivVO.getCertCode(), cusIndivVO.getEmail(), nlsApplyInfoVO.getMobile(), nlsApplyInfoVO.getIndivRsdAddr(), nlsApplyInfoVO.getLmtApplySeq());
            //    if (!psdContResult.isRetFlag()) {
            //        if (logger.isErrorEnabled()) {
            //            logger.error("【普税贷合同签订服务】用信申请流水号：" + applySeq + " 执行开户出现异常，异常信息为：" + psdContResult.getMsg());
            //            throw new OcmSystemException("【普税贷合同签订服务】用信申请流水号：" + applySeq + " 执行开户出现异常，异常信息为：" + psdContResult.getMsg());
            //        }
            //    } else {
            //        cusIndivVO.setAxqUsrId(psdContResult.getAxqUserId());
            //        signContractBean.setCusIndivVO(cusIndivVO);
            //    }
            //} else {
            //    int cusUpdNum = cusIndivService.updateByPk(cusIndivVO);
            //    if (cusUpdNum < 0) {
            //        if (logger.isErrorEnabled()) {
            //            logger.error("【普税贷合同签订服务】重跑时 更新安心签开户号到客户信息表出错! 用信申请流水号为:" + nlsApplyInfoVO.getApplySeq());
            //        }
            //        throw new OcmSystemException("【普税贷合同签订服务】重跑时 更新安心签开户号到客户信息表出错！");
            //    }
            //}

            // 调3203合同签订
            if (Objects.isNull(cfcaSignInfoVO)) {
                Map<String, String> ctrLoanContMetaData = psdApplyCtrLoanCtr.getCtrLoanContMetaData(nlsCreditInfoVO, getSOrg(nlsCreditInfoVO.getNlsOperOrgid()), nlsApplyInfoVO);
                // 保存脱敏合同处理记录到签章表
                insertTmSignRecord(nlsApplyInfoVO, ctrLoanContMetaData);
                PsdContResult psdContResult = psdContService.signature(nlsApplyInfoVO.getApplySeq(), cusIndivVO.getAxqUsrId(), "dkcont.pdf", "个人借款合同", ctrLoanContMetaData);
                if (!psdContResult.isRetFlag()) {
                    if (logger.isErrorEnabled()) {
                        logger.error("【普税贷合同签订服务】用信申请流水号：" + applySeq + " 执行合同签订出现异常，异常信息为" + psdContResult.getMsg());
                    }
                    throw new OcmSystemException(psdContResult.getMsg());
                }
                insertCfcaSignInfo(nlsCreditInfoVO, psdContResult, ConsoleConstant.CONT_TYPE_02, applySeq, cfcaSignInfoVO, signContractBean, nlsApplyInfoVO);
                updateCtrContInfo(applySeq, ConsoleConstant.CONT_TYPE_02);
            } else {
                CfcaSignInfoVO selectCfcaSignInfo = cfcaSignInfoService.queryByPk(cfcaSignInfoVO);
                if (selectCfcaSignInfo == null) {
                    int result = cfcaSignInfoService.insertCfcaSignInfo(cfcaSignInfoVO);
                    if (result < 0) {
                        if (logger.isErrorEnabled()) {
                            logger.error("【普税贷合同签订服务】重跑时 插入CFCA信息表出错！ 用信申请流水号为:" + nlsApplyInfoVO.getApplySeq());
                        }
                        throw new OcmSystemException("【普税贷合同签订服务】重跑时 插入CFCA信息表出错！");
                    }
                }
            }
            cfcaSignInfoVO = signContractBean.getCfcaSignInfoVO();
            // 调用cfca合同下载接口
            if (StringUtil.isEmpty(signContractBean.getFilePath()) &&
                    StringUtils.isNotEmpty(cfcaSignInfoVO.getCfcaContNo()) &&
                    ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname().equals(cfcaSignInfoVO.getCfcaSignState())) {
                PsdContResult psdContResult = psdContService.downSignFile(nlsApplyInfoVO.getApplySeq(), cfcaSignInfoVO.getCfcaContNo(), nlsApplyInfoVO.getApplySeq() + "_dkcont.pdf");

                if (!psdContResult.isRetFlag()) {
                    if (logger.isErrorEnabled()) {
                        logger.error("【普税贷合同签订服务】用信申请流水号：" + applySeq + " 执行合同下载出现异常，异常信息为" + psdContResult.getMsg());
                        throw new OcmSystemException("普税贷合同签订服务】用信申请流水号：" + applySeq + " 执行合同下载出现异常，异常信息为" + psdContResult.getMsg());
                    }
                }
                signContractBean.setFilePath(psdContResult.getFileFullPath());
                insertCert(nlsApplyInfoVO, signContractBean);
                // 插入操作
                insertImageBizDetail(nlsApplyInfoVO, PsdConstantSet.PSD_YX_CONT_TYPE, FilenameUtils.getBaseName(psdContResult.getFileFullPath()),psdContResult.getFileFullPath());
            } else if (StringUtils.isNotEmpty(signContractBean.getFilePath())) {
                insertCert(nlsApplyInfoVO, signContractBean);
            }
            // 流程状态
            nlsApplyInfoVO.setFlowStatus(FLOW_STATUS_4);

        } catch (Exception e) {
            logger.error(Arrays.toString(e.getStackTrace()));
            nlsProcessBizVo.setExceptionFlag(true);
            nlsProcessBizVo.setExceptionMsg(new OcmSystemException(e));
        } finally {
            logger.info("======>合同签订服务结束,流水号" + applySeq + "<======");
        }
    }

    private void insertCert(NlsApplyInfoVO nlsApplyInfoVO, SignContractBean signContractBean) throws OcmSystemException {
        int result = certUploadService.insert(signContractBean.getFilePath());
        if (result != 1) {
            if (logger.isErrorEnabled()) {
                logger.error("【普税贷合同签订服务】重跑时 插入上传信息表出错！ 用信申请流水号为:" + nlsApplyInfoVO.getApplySeq());
            }
            throw new OcmSystemException("【普税贷合同签订服务】重跑时 插入上传信息表出错！");
        }
    }

    /**
     * 根据客户ID获取客户信息
     */
    private CusIndivVO getCustInfo(String cusId) throws OcmSystemException {
        CusIndivVO cusIndivVO = new CusIndivVO();
        cusIndivVO.setCusId(cusId);
        cusIndivVO = cusIndivService.queryByPk(cusIndivVO);
        if (Objects.isNull(cusIndivVO)) {
            throw new OcmSystemException("根据客户号：" + cusId + "，查询到的客户信息为空！");
        }
        return cusIndivVO;
    }

    //private void execute3203(NlsCreditInfoVO nlsCreditInfoVO, String axqUserId, String contType, String applySeq, CfcaSignInfoVO cfcaSignInfoVO, SignContractBean signContractBean, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {
    //    if (logger.isInfoEnabled()){
    //        logger.info("======>【普税贷合同签订服务】 调用cfca合同模板签章接口【3203】,合同签章开始  用信申请流水号：" + applySeq);
    //    }
    //    ReqElectronicSignature3203Bean req3203Bean = new ReqElectronicSignature3203Bean();
    //    // 组装合同模板签章接口请求包信息
    //    ElectronicSignature3203BaseInfo req3203BeanBase = new ElectronicSignature3203BaseInfo();
    //    // 是否签署，0：抄送；1：签署；2：暂不签署；默认为0
    //    req3203BeanBase.setSignFlg(ElectronicSignatureConstant.IS_SIGN_2);
    //    // 印章ID = 客户开户号（安心签开户号） 印章ID
    //    req3203BeanBase.setSealId(axqUserId);
    //    // 合同类型
    //    req3203BeanBase.setContrTp(ElectronicSignatureConstant.CONTRACT_TYPE_CODE_JK);
    //    // 合同名称
    //    req3203BeanBase.setContrNm(loanContName);
    //
    //    // 关键字签章信息组装 start----------------------------------------------------------
    //    ElectronicSignature3203SignKeyWord signKeyword = new ElectronicSignature3203SignKeyWord();
    //    //关键字 = 银行签章
    //    signKeyword.setSignKwd(signKeyWord);
    //    //X轴偏移坐标
    //    signKeyword.setXOfstCoordPosn(xOfStcoordPosn);
    //    //Y轴偏移坐标
    //    signKeyword.setYOfstCoordPosn(yOfStcoordPosn);
    //    //签章图片宽度
    //    signKeyword.setSignImgWdth(signImgWdth);
    //    //签章图片高度
    //    signKeyword.setSignImgHght(signImgHght);
    //    // 关键字签章信息组装 ---------------------------------------------------------- end
    //    req3203BeanBase.setSignKeyword(signKeyword);
    //
    //    //[6]：签名域签章信息组装 start---------------------------------------------------------------------------------------
    //    List<ElectronicSignature3203SignPosnInfArry> signPosnInfArry = new ArrayList<ElectronicSignature3203SignPosnInfArry>();
    //    ElectronicSignature3203SignPosnInfArry signLocation1 = new ElectronicSignature3203SignPosnInfArry();
    //    //签名域页数
    //    signLocation1.setSignOnPgCnt("1");
    //    //签名域的左下角X轴坐标值
    //    signLocation1.setSignPosnLBX("85");
    //    //签名域的左下角Y轴坐标值
    //    signLocation1.setSignPosnLBY("550");
    //    //签名域的右上角X轴坐标值
    //    signLocation1.setSignPosnRUX("140");
    //    //签名域的右上角Y轴坐标值
    //    signLocation1.setSignPosnRUY("575");
    //    signPosnInfArry.add(signLocation1);
    //    //[6]：签名域签章信息组装 --------------------------------------------------------------------------------------- end
    //    req3203BeanBase.setSignPosnInfArry(signPosnInfArry);
    //
    //
    //    // 签署信息组装 start------------------------------------------------------------------------
    //    List<ElectronicSignature3203SignInfo> signInfos = new ArrayList<ElectronicSignature3203SignInfo>();
    //    ElectronicSignature3203SignInfo signInfo1 = new ElectronicSignature3203SignInfo();
    //    //用户ID = 安心签开户号  @modify @date 2019/06/10
    //    signInfo1.setUsrID(axqUserId);
    //    //授权时间
    //    signInfo1.setAuthTm(TimeUtil.getTimeStampByPattern("yyyyMMddHHmmss"));
    //    //授权地址
    //    signInfo1.setAuthAddr(authaddr);
    //    //项目编号
    //    signInfo1.setPrjNo(UUIDUtil.getUUID());
    //
    //    //按关键字创建签名  @modify @date 2019/06/10
    //    ElectronicSignature3203SignKeyWord2 signKeyWord2 = new ElectronicSignature3203SignKeyWord2();
    //    //关键字 = 客户签章
    //    signKeyWord2.setSignKwd(signKeyWordCust);
    //    signKeyWord2.setXOfstCoordPosn(xOfStcoordPosn);
    //    signKeyWord2.setYOfstCoordPosn(yOfStcoordPosn);
    //    signKeyWord2.setSignImgHght(signImgHght);
    //    signKeyWord2.setSignImgWdth(signImgWdth);
    //    signInfo1.setSignKeyword2(signKeyWord2);
    //    //是否代签 1 代签
    //    signInfo1.setAgncSignFlg("0");
    //    signInfo1.setCopyFlg("0");
    //    signInfos.add(signInfo1);
    //    // 签署信息组装 ------------------------------------------------------------------------ end
    //    req3203BeanBase.setSignBscInfArry(signInfos);
    //    // 获取合同流
    //    Map<String, String> ctrLoanContMetaData = psdApplyCtrLoanCtr.getCtrLoanContMetaData(nlsCreditInfoVO, getSOrg(nlsCreditInfoVO.getNlsOperOrgid()), nlsApplyInfoVO);
    //    req3203Bean.setContrFlStrm(sedCfcaService.createLocalContract(contType,ctrLoanContMetaData));
    //    req3203Bean.setUploadContract(req3203BeanBase);
    //    RspElectronicSignature3203BaseBean resp3203BaseBean = new RspElectronicSignature3203BaseBean();
    //    try {
    //        RspElectronicSignature3203Bean resp3203Bean = sedCfcaService.signContract(req3203Bean);
    //
    //        resp3203BaseBean = Optional.ofNullable(resp3203Bean.getContract()).orElseGet(RspElectronicSignature3203BaseBean::new);
    //        if (Objects.isNull(resp3203BaseBean)) {
    //            if (logger.isErrorEnabled()){
    //                logger.error("【普税贷合同签订服务】调用cfca合同模板签章接口【3203】，返回的合同签署信息为空! 用信申请流水号：" + applySeq);
    //            }
    //            throw new Exception("【普税贷合同签订服务】调用cfca合同模板签章接口【3203】，返回的合同签署信息为空! 用信申请流水号：" + applySeq);
    //        }
    //        ElectronicSignature3203Signatory respSignature3203Signatory = Optional.ofNullable(resp3203BaseBean.getContractSignInfArry().get(0)).orElseGet(ElectronicSignature3203Signatory::new);
    //        if (Objects.isNull(respSignature3203Signatory)) {
    //            if (logger.isErrorEnabled()){
    //                logger.error("【普税贷合同签订服务】调用cfca合同模板签章接口【3203】，返回的签署人信息为空! 用信申请流水号：" + applySeq);
    //            }
    //            throw new Exception("【普税贷合同签订服务】调用cfca合同模板签章接口【3203】，返回的签署人信息为空! 用信申请流水号：" + applySeq);
    //        }
    //        if (logger.isInfoEnabled()){
    //            logger.info("【普税贷合同签订服务】调用cfca合同模板签章接口【3203】结束。 用信申请流水号：" + applySeq + "返回结果为：" + JSON.toJSONString(resp3203BaseBean));
    //        }
    //    } catch (Exception e) {
    //        if (logger.isErrorEnabled()){
    //            logger.error("【普税贷合同签订服务】用信申请流水号：" + applySeq + " 执行合同签订出现异常，异常信息为：" + e.getMessage());
    //        }
    //        throw new ExternalSysException("【普税贷合同签订服务】用信申请流水号：" + applySeq + " 执行合同签订出现异常，异常信息为：" + e.getMessage());
    //    }
    //    if (logger.isInfoEnabled()){
    //        logger.info("======>【普税贷合同签订服务】 调用cfca合同模板签章接口【3203】,合同签章结束  用信申请流水号：" + applySeq);
    //    }
    //
    //}


    /**
     * 通过用信申请流水号、合同类型获取合同号
     */
    private String getContNo(String applySeq, String contType) throws OcmSystemException {
        CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
        ctrLoanContVO.setSerno(applySeq);
        ctrLoanContVO.setContType(contType);
        ctrLoanContVO = ctrLoanContService.qryBySernoAndContTyp(ctrLoanContVO);
        if (Objects.isNull(ctrLoanContVO)) {
            logger.error("普税贷【合同签订服务】通过用信申请流水号、合同类型获取到合同信息为空！");
            throw new OcmSystemException("普税贷用信申请【合同签订服务】通过用信申请流水号、合同类型获取到合同信息为空！");
        }
        String ctrContNo = ctrLoanContVO.getContNo();
        if (StringUtil.isNullorBank(ctrContNo)) {
            logger.error("普税贷【合同签订服务】通过用信申请流水号、合同类型查询合同信息，得到的合同号为空！");
            throw new OcmSystemException("普税贷用信申请【合同签订服务】通过用信申请流水号、合同类型查询合同信息，得到的合同号为空！");
        }
        return ctrContNo;

    }

    /**
     * 保存合同签章记录
     *
     * @throws OcmSystemException
     * @author qiuyf
     * @version 0.1 初始为0.1,后续变更则修改
     * @since 2019年4月26日 上午10:53:53
     */
    private void insertCfcaSignInfo(NlsCreditInfoVO nlsCreditInfoVO, PsdContResult psdContResult, String contType, String applySeq, CfcaSignInfoVO cfcaSignInfoVO, SignContractBean signContractBean, NlsApplyInfoVO nlsApplyInfoVO) throws OcmSystemException {
        String contNo = this.getContNo(applySeq, contType);
        if (logger.isInfoEnabled()) {
            logger.info("======>普税贷用信申请【合同签订服务】保存合同签章记录信息开始<===== 用信申请流水号为：" + applySeq + " 合同号为：" + contNo);
        }
        cfcaSignInfoVO = Optional.ofNullable(cfcaSignInfoVO).orElse(new CfcaSignInfoVO());
        //申请流水号
        cfcaSignInfoVO.setApplySeq(applySeq);
        //产品id
        cfcaSignInfoVO.setPrdId(nlsCreditInfoVO.getPrdId());
        //产品代码
        cfcaSignInfoVO.setPrdCode(nlsCreditInfoVO.getPrdCode());
        //产品名称
        cfcaSignInfoVO.setPrdName(nlsCreditInfoVO.getPrdName());
        //合同号
        cfcaSignInfoVO.setContNo(contNo);
        //安心签合同号
        cfcaSignInfoVO.setCfcaContNo(psdContResult.getAxqContNo());
        //客户号
        cfcaSignInfoVO.setCusId(nlsCreditInfoVO.getCusId());
        //客户名称
        cfcaSignInfoVO.setCusName(nlsCreditInfoVO.getCusName());
        //渠道号
        cfcaSignInfoVO.setPrdType(nlsCreditInfoVO.getChannelNo());
        // 网贷经办机构
        cfcaSignInfoVO.setNlsOperOrgid(nlsCreditInfoVO.getNlsOperOrgid());
        // 网贷经办人
        cfcaSignInfoVO.setNlsOperUserid(nlsCreditInfoVO.getNlsOperUserid());
        // 账务机构
        cfcaSignInfoVO.setFinaBrId(nlsCreditInfoVO.getNlsOperOrgid());
        //cfca签署状态 = “未签署”
        cfcaSignInfoVO.setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
        signContractBean.setCfcaSignInfoVO(cfcaSignInfoVO);
        nlsApplyInfoVO.setSignContractBean(signContractBean);
        cfcaSignInfoVO.setCfcaSignTime(psdContResult.getAxqSignTime());
        int num = cfcaSignInfoService.insertCfcaSignInfo(cfcaSignInfoVO);
        if (num < 0) {
            if (logger.isErrorEnabled()) {
                logger.error("普税贷用信申请【合同签订服务】用信申请流水号为: " + applySeq + "合同号为：" + contNo + " 往cfca加签信息表新增数据出错!");
            }
            throw new OcmSystemException("普税贷用信申请【合同签订服务】用信申请流水号为: " + applySeq + "合同号为：" + contNo + " 往cfca加签信息表新增数据出错!");
        }
        if (logger.isInfoEnabled()) {
            logger.info("======>普税贷用信申请【合同签订服务】保存合同签章记录信息结束<===== 用信申请流水号为：" + applySeq + " 合同号为：" + contNo);
        }
    }

    /**
     * 签章接口
     */
    //private void execute3207(NlsCreditInfoVO nlsCreditInfoVO, String cfcaContNo, String contType, String applySeq, SignContractBean signContractBean, NlsApplyInfoVO nlsApplyInfoVO) throws Exception {
    //    logger.info("======> 【普税贷用信申请合同签订服务】调用cfca关键字签署接口【3207】，合同签章开始<====== 用信申请流水号：" + applySeq);
    //
    //    ReqElectronicSignature3207Bean req3207Bean = new ReqElectronicSignature3207Bean();
    //
    //    ReqElectronicSignature3207Struct signCtrByKyd3207 = new ReqElectronicSignature3207Struct();
    //    //安心签合同号
    //    signCtrByKyd3207.setContractNo(cfcaContNo);
    //    //组装印章的位置确定信息--------------------- start
    //    ReqElecTronicSignature3207SignKeyWordInfo signKeyword = new ReqElecTronicSignature3207SignKeyWordInfo();
    //    // 关键字
    //    signKeyword.setKeyword(signKeyWord);
    //    // X轴偏移坐标
    //    signKeyword.setOffsetCoordX(xOfStcoordPosn);
    //    // Y轴偏移坐标
    //    signKeyword.setOffsetCoordY(yOfStcoordPosn);
    //    // 签章图片宽度
    //    signKeyword.setImageWidth(signImgWdth);
    //    // 签章图片高度
    //    signKeyword.setImageHeight(signImgHght);
    //    //组装印章的位置确定信息--------------------- end
    //    signCtrByKyd3207.setSignKeyword(signKeyword);
    //
    //    //组装印章的详细信息-------------------------------------------------------------------------------------------------start
    //    ReqElecTronicSignature3207SignSealInfo signSealInfo = new ReqElecTronicSignature3207SignSealInfo();
    //    /**
    //     * 根据配置主键、参数值，查参数配置表  TODO 根据机构号获取配置主键，从而获取机构开户号
    //     */
    //    SCfgParamVO sCfgParamVO = new SCfgParamVO();
    //    sCfgParamVO.setParamKey(ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue());
    //    sCfgParamVO = sCfgParamService.queryByCondition(sCfgParamVO);
    //    if (Objects.isNull(sCfgParamVO)) {
    //        if (logger.isErrorEnabled()){
    //            logger.error("【普税贷用信申请合同签订服务】 根据主键值" + ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue() + "，无法获取机构cfca开户号初始化信息为空，请核查是否初始化数据表！");
    //        }
    //        throw new OcmSystemException("【普税贷用信申请合同签订服务】 根据主键值" + ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue() + "，无法获取机构cfca开户号初始化信息为空，请核查是否初始化数据表！");
    //    } else {
    //        if (StringUtil.isNullorBank(sCfgParamVO.getParamValue())) {
    //            if (logger.isErrorEnabled()){
    //                logger.error("【普税贷用信申请合同签订服务】根据主键值" + ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue() + "，获取到的机构开户号为空，请核查是否初始化数据表！");
    //            }
    //            throw new OcmSystemException("【普税贷用信申请合同签订服务】根据主键值" + ConsoleEnums.ParamKey.GCB_BANK_CFCA_USR_ID.getValue() + "，获取到的机构开户号为空，请核查是否初始化数据表！");
    //        }
    //    }
    //    // 用户ID（广州银行已在cfca开过户，该值是初始化在表中的）
    //    signSealInfo.setUserId(sCfgParamVO.getParamValue());
    //    // 授权时间
    //    signSealInfo.setAuthorizationTime(TimeUtil.getTimeStampByPattern("yyyyMMddHHmmss"));
    //    // 授权地点
    //    signSealInfo.setLocation(authaddr);
    //    // 项目编号
    //    signSealInfo.setProjectCode(UUIDUtil.getUUID());
    //    /** 是否检查项目编号 （0：不检查；1：检查；默认为0，需要校验项目编号的时候传送）*/
    //    // 签章图片 （需要根据业务数据的经办机构号，到本地路径 /home/xxx/下放置的银行开户影像信息，找到机构号对应的签章信息） 文件命名规范：xx银行签署图orgCode.xx，文件的结尾一定是银行唯一的机构号
    //    signSealInfo.setImageData(getImageDataStr(nlsCreditInfoVO.getNlsOperOrgid()));
    //
    //    /** 印章ID （添加印章返回的印章ID，不传时为默认印章）*/
    //    //组装印章的详细信息--------------------------------------------------------------------------------------------------------end
    //    signCtrByKyd3207.setSignSealInfo(signSealInfo);
    //
    //    req3207Bean.setSignContractByKeyword(signCtrByKyd3207);
    //
    //    RespElectronicSignature3207Bean resp3207Bean = new RespElectronicSignature3207Bean();
    //    try {
    //        //resp3207Bean = sedCfcaService.signSeal(req3207Bean);
    //        if (Objects.isNull(resp3207Bean)) {
    //            if (logger.isErrorEnabled()){
    //                logger.error("调用cfca关键字签署接口【3207】，返回的签署信息为空，合同签署失败！ 用信申请流水号：" + nlsApplyInfoVO.getApplySeq());
    //            }
    //            throw new Exception("调用cfca关键字签署接口【3207】，返回的签署信息为空，合同签署失败！ 用信申请流水号：" + nlsApplyInfoVO.getApplySeq());
    //        }
    //    } catch (Exception e) {
    //        if (logger.isErrorEnabled()){
    //            logger.error("调用cfca关键字签署接口【3207】用信申请流水号：" + nlsApplyInfoVO.getApplySeq() + "执行合同签订出现异常，异常信息为：" + e.getMessage());
    //        }
    //        throw new ExternalSysException("调用cfca关键字签署接口【3207】用信申请流水号：" + nlsApplyInfoVO.getApplySeq() + "执行合同签订出现异常，异常信息为：" + e.getMessage());
    //    }
    //    signContractBean.getCfcaSignInfoVO().setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
    //    if (logger.isInfoEnabled()){
    //        logger.info("调用cfca关键字签署接口【3207】用信申请流水号：" + nlsApplyInfoVO.getApplySeq() + "调用cfca关键字签署接口【3207】结束。返回结果为：" + JSON.toJSONString(resp3207Bean));
    //    }
    //    // 更新cfca加签信息
    //    updCfcaSignInfo(getContNo(applySeq, contType));
    //    // 更新合同信息
    //    updateCtrContInfo(applySeq, contType);
    //}

    /**
     * 更新合同信息
     */
    private void updateCtrContInfo(String applySeq, String contType) throws OcmSystemException {
        CtrLoanContVO ctrLoanContVO = new CtrLoanContVO();
        ctrLoanContVO.setSerno(applySeq);
        ctrLoanContVO.setContType(contType);
        ctrLoanContVO = ctrLoanContService.qryBySernoAndContTyp(ctrLoanContVO);
        if (Objects.isNull(ctrLoanContVO)) {
            logger.error("普税贷【合同签订服务】通过用信申请流水号、合同类型获取到合同信息为空！");
            throw new OcmSystemException("普税贷用信申请【合同签订服务】通过用信申请流水号、合同类型获取到合同信息为空！");
        }
        //合同状态 已签订
        ctrLoanContVO.setContState(CONT_STATUS_200);
        int result = ctrLoanContService.updateByPk(ctrLoanContVO);
        if (result != 1) {
            logger.error("普税贷【合同签订服务】通过用信申请流水号、合同类型更新合同信息为已签订出现异常！");
            throw new OcmSystemException("普税贷【合同签订服务】通过用信申请流水号、合同类型更新合同信息为已签订出现异常");
        }
    }


    /**
     * 通过机构号获取指定路径下的签章图片信息
     */
    //private String getImageDataStr(String orgCode) throws OcmSystemException {
    //    if (StringUtil.isNullorBank(orgCode)) {
    //        throw new OcmSystemException("授信申请经办机构号为空，无法获取指定路径下的签章图片信息！");
    //    }
    //    String imageData = null;
    //    //获取指定路径下的文件信息
    //    File[] files = new File(imagesAddr).listFiles();
    //    if (null == files || files.length == 0) {
    //        throw new OcmSystemException("路径【：" + imagesAddr + "】，不存在相关的文件信息，请核查!");
    //    }
    //    for (int i = 0; i < files.length; i++) {
    //        if (files[i].isDirectory()) {
    //            continue;
    //        }
    //        //获取文件名称
    //        String fileName = files[i].getName().substring(0, files[i].getName().lastIndexOf("."));
    //        if (fileName.endsWith(orgCode)) {
    //            try {
    //                imageData = Base64.encodeBytes(FileUtil.toByteArray(files[i]));
    //            } catch (IOException e) {
    //                logger.error("处理cfca关键字签署接口【3207】，签章图片处理失败！", e);
    //                throw new OcmSystemException("签章图片处理异常，调用cfca关键字签署接口【3207】失败！");
    //            }
    //        }
    //    }
    //    if (StringUtil.isNullorBank(imageData)) {
    //        throw new OcmSystemException("在路径【：" + imagesAddr + "】下，找不到机构标识为【" + orgCode + "】的签章图片信息，请核查！");
    //    }
    //    return imageData;
    //}

    /**
     * 更新cfca加签信息签署状态为“已签署”
     */
    private void updCfcaSignInfo(String contNo) throws OcmSystemException {
        CfcaSignInfoVO cfcaSignInfoVO = new CfcaSignInfoVO();
        cfcaSignInfoVO.setContNo(contNo);
        cfcaSignInfoVO = cfcaSignInfoService.queryByPk(cfcaSignInfoVO);
        if (Objects.isNull(cfcaSignInfoVO)) {
            if (logger.isErrorEnabled()) {
                logger.error("调用cfca关键字签署接口【3207】根据合同号【" + contNo + "】，查询到的cfca加签信息为空！");
            }
            throw new OcmSystemException("根据合同号【" + contNo + "】，查询到的cfca加签信息为空！");
        }
        cfcaSignInfoVO.setCfcaSignState(ElectronicSignatureEnums.CfcaSignmentStateEnum.SIGN.getEnname());
        int result = cfcaSignInfoService.updateByPk(cfcaSignInfoVO);
        if (result != 1) {
            if (logger.isErrorEnabled()) {
                logger.error("调用cfca关键字签署接口【3207】根据合同号【" + contNo + "】，更新cfca加签信息失败！");
            }
            throw new OcmSystemException("调用cfca关键字签署接口【3207】根据合同号【" + contNo + "】，更新cfca加签信息失败");

        }
    }

    /**
     * 获取机构信息
     */
    private SOrgVO getSOrg(String orgCode) throws OcmSystemException {
        SOrgVO sOrgVO = new SOrgVO();
        sOrgVO.setOrgCode(orgCode);
        sOrgVO = sOrgService.queryByPk(sOrgVO);
        if (Objects.isNull(sOrgVO)) {
            throw new OcmSystemException("通过机构号【" + orgCode + "】，获取到机构信息为空！");
        }
        return sOrgVO;
    }

    /**
     * 获取额度协议信息
     */
    private LmtPrdContVO getLmtPrdCont(String lmtApplySeq) throws OcmSystemException {
        LmtPrdContVO lmtPrdContVO = lmtPrdContService.qryLmtPrdContByLmtApplySeq(lmtApplySeq);
        if (Objects.isNull(lmtPrdContVO)) {
            throw new OcmSystemException("通过授信申请流水号【" + lmtApplySeq + "】，获取到授信协议信息为空！");
        }
        if (null == lmtPrdContVO.getLmtAmt()) {
            throw new OcmSystemException("通过授信申请流水号【" + lmtApplySeq + "】，获取到授信额度为空！");
        }
        return lmtPrdContVO;
    }

    /**
     * 根据日期与日期单位获取数值
     */
    private String getDateString(String date, String dateType) throws OcmSystemException {
        if (!Flag) {
            try {
                MessageRuleCheckUtil.checkDate("授信有效日期", date, "yyyy-MM-dd");
                Flag = true;
            } catch (BizException e) {
                throw new OcmSystemException("组装合同参数时，校验到授信协议信息表的有效日期不符合格式“yyyy-MM-dd”");
            }
        }
        String result = "";
        String[] dates = date.split("-");
        if (TimeType.YEAR.getKey().equals(dateType)) {
            result = dates[0];
        } else if (TimeType.MONTH.getKey().equals(dateType)) {
            result = dates[1];
        } else if (TimeType.DAY.getKey().equals(dateType)) {
            result = dates[2];
        }
        return result;
    }

    @Autowired
    @Qualifier("cusIndivService")
    private CusIndivService cusIndivService;

    @Autowired
    @Qualifier("cfcaSignInfoService")
    private CfcaSignInfoService cfcaSignInfoService;


    @Autowired
    @Qualifier("ctrLoanContService")
    private CtrLoanContService ctrLoanContService;

    @Autowired
    @Qualifier("lmtPrdContService")
    private LmtPrdContService lmtPrdContService;

    @Autowired
    @Qualifier("nlsCreditInfoService")
    private NlsCreditInfoService nlsCreditInfoService;

    @Autowired
    @Qualifier("psdCertUploadService")
    private PsdCertUploadService certUploadService;

    @Autowired
    @Qualifier("sOrgService")
    private SOrgService sOrgService;

    @Autowired
    private PsdApplyCtrLoanCtr psdApplyCtrLoanCtr;

    @Autowired
    private PsdContService psdContService;

    @Autowired
    private ImageBizDetailService imageBizDetailService;

    @Autowired
    private PsdSqsSignatureService sqsSignatureService;

    private void insertImageBizDetail(NlsApplyInfoVO nlsApplyInfoVO, String imgType, String fileName, String filePath) {
        ImageBizDetailVO imageBizDetail = new ImageBizDetailVO();
        imageBizDetail.setApplySeq(nlsApplyInfoVO.getApplySeq());
        imageBizDetail.setBizStage("用信合同");
        imageBizDetail.setFileDesc("普税贷用信合同");
        imageBizDetail.setFileName(fileName);
        imageBizDetail.setFilePath(filePath);
        imageBizDetail.setImageId(imgType);
        imageBizDetail.setCreateTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
        imageBizDetail.setImageType(imgType);
        imageBizDetailService.insertImageBizDetail(imageBizDetail);
    }

    private void insertTmSignRecord(NlsApplyInfoVO nlsApplyInfoVO, Map<String, String> ctrLoanContMetaData) {
        //脱敏数据
        SignatureRecordVO tmSignatureRecordVO = new SignatureRecordVO();
        tmSignatureRecordVO.setId(UUIDUtil.getUUID());
        tmSignatureRecordVO.setPrdId(PsdConstantSet.prdId);
        tmSignatureRecordVO.setApplySeq(nlsApplyInfoVO.getApplySeq());
        tmSignatureRecordVO.setLinkType(4);
        tmSignatureRecordVO.setPolFileType(PsdConstantSet.PSD_YX_CONT_TM_TYPE);
        tmSignatureRecordVO.setRetryNum(0);
        tmSignatureRecordVO.setCreateTime(new Date());
        tmSignatureRecordVO.setLastUpdateTime(new Date());
        tmSignatureRecordVO.setSiuSta(0);
        tmSignatureRecordVO.setSiuFillInfo(JSONObject.toJSONString(ctrLoanContMetaData));
        sqsSignatureService.insertRecord(tmSignatureRecordVO);
    }
}
